<template>
  <view class="bill-container">
    <!-- 顶部汇总卡片 -->
    <view class="summary-card" :class="currentTab">
      <text class="title">{{currentTab === 'income' ? '总收入' : '总支出'}}</text>
      <text class="amount">¥{{totalAmount.toFixed(2)}}</text>
      <view class="tab-switch">
        <text 
          class="tab-item" 
          :class="{active: currentTab === 'income'}"
          @click="switchTab('income')"
        >
          收入
        </text>
        <text 
          class="tab-item" 
          :class="{active: currentTab === 'expense'}"
          @click="switchTab('expense')"
        >
          支出
        </text>
      </view>
    </view>
    
    <!-- 月份选择器 -->
    <view class="month-selector">
      <uni-icons type="left" size="20" color="#666" @click="prevMonth"></uni-icons>
      <text class="month-text">{{displayMonth}}</text>
      <uni-icons type="right" size="20" color="#666" @click="nextMonth"></uni-icons>
    </view>
    
    <!-- 账单列表 -->
    <scroll-view 
      class="bill-list" 
      scroll-y 
      @scrolltolower="loadMoreData"
      :scroll-with-animation="true"
    >
      <view 
        class="bill-item" 
        v-for="(item, index) in billData" 
        :key="item.id"
      >
        <view class="item-left">
          <view class="icon" :style="{backgroundColor: getCategoryColor(item.category)}">
            <uni-icons :type="getCategoryIcon(item.category)" size="20" color="#fff"></uni-icons>
          </view>
          <view class="info">
            <text class="title">{{item.title}}</text>
            <text class="date">{{formatTime(item.time)}}</text>
          </view>
        </view>
        <text class="amount" :class="item.type">¥{{item.amount.toFixed(2)}}</text>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <uni-icons type="spinner-cycle" size="20" color="#999" class="loading-icon"></uni-icons>
        <text>加载中...</text>
      </view>
      
      <!-- 没有更多数据提示 -->
      <view class="no-more" v-if="noMoreData && billData.length > 0">
        <text>已经到底了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="billData.length === 0 && !loading">
        <image src="/static/images/empty-bill.png" mode="aspectFit"></image>
        <text>本月暂无{{currentTab === 'income' ? '收入' : '支出'}}记录</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    const now = new Date()
    return {
      currentTab: 'income',
      currentMonth: now.getMonth() + 1,
      currentYear: now.getFullYear(),
      totalAmount: 0,
      billData: [],
      loading: false,
      page: 1,
      pageSize: 10,
      noMoreData: false,
      categories: {
        salary: { name: '工资', icon: 'wallet', color: '#FF9F43' },
        parttime: { name: '兼职', icon: 'hand-up', color: '#28C76F' },
        reward: { name: '跑腿', icon: 'paperplane', color: '#00CFE8' },
        food: { name: '餐饮', icon: 'shop', color: '#EA5455' },
        shopping: { name: '购物', icon: 'cart', color: '#7367F0' },
        transport: { name: '交通', icon: 'bus', color: '#32CCBC' }
      }
    }
  },
  computed: {
    displayMonth() {
      return `${this.currentYear}年${this.currentMonth}月`
    }
  },
  onLoad() {
    this.loadBillData()
  },
  methods: {
    // 切换收入/支出tab
    switchTab(tab) {
      if (this.currentTab === tab) return
      this.currentTab = tab
      this.resetList()
      this.loadBillData()
    },
    
    // 上一个月
    prevMonth() {
      if (this.currentMonth === 1) {
        this.currentMonth = 12
        this.currentYear--
      } else {
        this.currentMonth--
      }
      this.resetList()
      this.loadBillData()
    },
    
    // 下一个月
    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentMonth = 1
        this.currentYear++
      } else {
        this.currentMonth++
      }
      this.resetList()
      this.loadBillData()
    },
    
    // 重置列表数据
    resetList() {
      this.page = 1
      this.billData = []
      this.noMoreData = false
      this.totalAmount = 0
    },
    
    // 格式化时间显示
    formatTime(timeStr) {
      return timeStr.slice(5, 16).replace('-', '月').replace(' ', '日 ')
    },
    
    // 获取分类图标
    getCategoryIcon(category) {
      return this.categories[category]?.icon || 'help'
    },
    
    // 获取分类颜色
    getCategoryColor(category) {
      return this.categories[category]?.color || '#B9B9C3'
    },
    
    // 加载账单数据
    async loadBillData() {
      if (this.loading) return
      
      this.loading = true
      uni.showLoading({ title: '加载中...' })
      
      try {
        // 这里替换为实际API调用
        const newData = await this.fetchBillData()
        this.billData = newData
        this.totalAmount = newData.reduce((sum, item) => sum + item.amount, 0)
        
        // 判断是否还有更多数据
        this.noMoreData = newData.length < this.pageSize
      } catch (error) {
        console.error('加载账单失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.hideLoading()
      }
    },
    
    // 加载更多数据
    async loadMoreData() {
      if (this.loading || this.noMoreData) return
      
      this.loading = true
      this.page++
      
      try {
        // 这里替换为实际API调用
        const newData = await this.fetchBillData()
        this.billData = [...this.billData, ...newData]
        
        // 判断是否还有更多数据
        this.noMoreData = newData.length < this.pageSize
      } catch (error) {
        console.error('加载更多失败:', error)
        this.page-- // 加载失败时回退页码
      } finally {
        this.loading = false
      }
    },
    
    // 模拟API请求
    fetchBillData() {
      return new Promise(resolve => {
        setTimeout(() => {
          const count = this.page === 3 ? 4 : this.pageSize // 模拟第三页数据不足
          const categoryKeys = Object.keys(this.categories)
          const filteredCategories = categoryKeys.filter(key => 
            this.categories[key].name !== (this.currentTab === 'income' ? '购物' : '工资')
          )
          
          const newData = Array.from({ length: count }, (_, i) => {
            const category = filteredCategories[Math.floor(Math.random() * filteredCategories.length)]
            const amount = parseFloat((Math.random() * 500 + 10).toFixed(2))
            const day = Math.floor(Math.random() * 28) + 1
            const hour = Math.floor(Math.random() * 24)
            const minute = Math.floor(Math.random() * 60)
            
            return {
              id: `bill-${this.page}-${i}`,
              type: this.currentTab,
              title: this.categories[category].name,
              category: category,
              amount: amount,
              time: `${this.currentYear}-${this.currentMonth.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
            }
          })
          
          resolve(newData)
        }, 800)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.bill-container {
  height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  
  .summary-card {
    padding: 40rpx 30rpx;
    border-radius: 0 0 30rpx 30rpx;
    color: #fff;
    position: relative;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    
    &.income {
      background: linear-gradient(135deg, #28C76F, #3BB78F);
    }
    
    &.expense {
      background: linear-gradient(135deg, #EA5455, #F29263);
    }
    
    .title {
      font-size: 28rpx;
      opacity: 0.9;
    }
    
    .amount {
      font-size: 48rpx;
      font-weight: bold;
      margin: 15rpx 0 40rpx;
      display: block;
    }
    
    .tab-switch {
      display: flex;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 30rpx;
      padding: 6rpx;
      
      .tab-item {
        flex: 1;
        text-align: center;
        padding: 12rpx;
        border-radius: 30rpx;
        font-size: 28rpx;
        transition: all 0.3s;
        
        &.active {
          background-color: #fff;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
  
  .month-selector {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30rpx 0;
    background-color: #fff;
    margin: 20rpx 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .month-text {
      font-size: 32rpx;
      margin: 0 40rpx;
      color: #333;
      font-weight: 500;
    }
    
    uni-icons {
      padding: 10rpx;
    }
  }
  
  .bill-list {
    flex: 1;
    padding: 0 30rpx;
    box-sizing: border-box;
    
    .bill-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      background-color: #fff;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: transform 0.2s;
      
      &:active {
        transform: scale(0.98);
      }
      
      .item-left {
        display: flex;
        align-items: center;
        flex: 1;
        overflow: hidden;
        
        .icon {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;
          flex-shrink: 0;
        }
        
        .info {
          display: flex;
          flex-direction: column;
          flex: 1;
          min-width: 0;
          
          .title {
            font-size: 30rpx;
            color: #333;
            margin-bottom: 8rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .date {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
      
      .amount {
        font-size: 32rpx;
        font-weight: 500;
        margin-left: 20rpx;
        flex-shrink: 0;
        
        &.income {
          color: #28C76F;
        }
        
        &.expense {
          color: #EA5455;
        }
      }
    }
    
    .loading-state {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 30rpx 0;
      color: #999;
      font-size: 28rpx;
      
      .loading-icon {
        margin-right: 15rpx;
        animation: rotating 1s linear infinite;
      }
    }
    
    .no-more {
      text-align: center;
      padding: 30rpx 0;
      color: #999;
      font-size: 28rpx;
    }
    
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 100rpx 0;
      text-align: center;
      
      image {
        width: 300rpx;
        height: 300rpx;
        margin-bottom: 30rpx;
        opacity: 0.6;
      }
      
      text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>